<?php
declare (strict_types = 1);

namespace app\middleware;

use app\model\User;
use app\tools\ResponseTool;
use think\facade\Cache;
use think\facade\Log;

class TokenVerify
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $controllerName = strtolower($request->controller());
        Log::record($controllerName);
        $token = $request->header('userToken') ? $request->header('userToken') : '';
        if ($controllerName == 'login' || $controllerName == 'register' || $controllerName == 'passwordforget' || $controllerName == 'gettelcode') {
            return $next($request);
        } else {
            if (!$token) {
                return ResponseTool::getRs('PARAM_ERROR', [], '令牌已过期');
            } else {
                if ($token == Cache::get($request->header('userName'))) {
                    return $next($request);
                } else {
                    return ResponseTool::getRs('PARAM_ERROR', [], '令牌已过期');
                }
            }
        }
        return $next($request);

    }
}
